<template>
  <div class="header">
    <span class="txt">全选</span>
    <input type="checkbox" name="" id="" class="ck" v-model="allCheck" />
    <span class="txt">/</span>
    <span class="txt">反选</span>
    <input
      type="checkbox"
      name=""
      id=""
      class="ck"
      :checked="oppChecked"
      ref="opp"
      @change="oppChange"
    />
    <button class="btn" @click="delItems">删除 {{ ck_num }} 封</button>
  </div>
</template>

<script setup>
import {
  nextTick,
  onBeforeMount,
  onBeforeUpdate,
  onMounted,
  onUpdated,
} from "vue";
import mitts from "../bus";
import { usedelItemsHook } from "./Hooks/useDelItemsHooks";
const { delItems } = usedelItemsHook();
const list = ref([]);
mitts.on("giveList", (e) => {
  list.value = e;
});
const ck_num = computed(() => {
  return list.value.reduce((sum, item) => {
    if (item.isSelected) {
      return sum + 1;
    }
    return sum;
  }, 0);
});
const allCheck = computed({
  get() {
    return list.value.every((item) => item.isSelected === true);
  },
  set(val) {
    return list.value.forEach((item) => (item.isSelected = val));
  },
});
const opp = ref(null);
onBeforeMount(() => {
  // console.log('onBeforeMount')
});
onMounted(() => {
  // console.log('onMounted')
});
onBeforeUpdate(() => {
  // console.log("onBeforeUpdate");
});
onUpdated(() => {
  // console.log("onUpdated");
});
const oppChecked = computed({
  get() {
    const res = list.value.every((item) => item.isSelected === true);
    // 也还是要手动更新一下,通过ref属性
    //【或如后方，通过e.target和nextTick】
    console.log(333);
    if (opp.value) {
      // opp.value.checked = res;
    }

    // debugger;
    return res;
  },
});
const oppChange = (e) => {
  console.log(999)
  console.log(oppChecked.value);
  // 此时计算属性的依赖还没有变化，访问计算属性，
  // 它不会重新计算，而是会直接采用之前的值。
  e.target.checked = oppChecked.value;
  nextTick(() => {
    // debugger;
    // 到这个时候，计算属性的依赖以及变化了，
    // 所以此时，访问计算属性，拿到的就是变化之后的新值。
    // PS.此时如果不访问，这个计算属性会稍晚一些调用。
    // PS.如果此时就访问了，那这个计算属性就会在这时
    // PS.去调用。
    // console.log(oppChecked.value);
    // e.target.checked = oppChecked.value;
    // console.log(555);
    nextTick(() => {
      // console.log(666);
    });
  });
  mitts.emit("changeOpp");
  // debugger;
};
</script>

<style lang="scss" scoped>
.header {
  margin-bottom: 20px;
  .txt {
    margin-right: 5px;
    font-weight: 700;
  }
  .ck {
    margin-right: 5px;
  }
  .btn {
    border: 2px solid #000;
    padding-block: 2px;
    padding-inline: 4px;
    background-color: #ff4051;
    font-size: 12px;
  }
}
</style>
